//
//  HMComposeViewController.swift
//  webo
//
//  Created by apple on 2016/11/21.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

private let btnTag = 1000
let colCount:CGFloat = 3
let comMargin:CGFloat = 4
let comColwidth = (ScreenWidth - comMargin * (colCount + 1)) / colCount
enum toolStyle: NSInteger {
    case Picture = 1000
    case Atsome
    case Topic
    case Emotion
    case More
}

class HMComposeViewController: UIViewController {
// MARK: - 程序入口
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        setupUI()
    }
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imgName: "", target: self, action: #selector(close))
        setupTitle()
        setSendUIBarButton()
        addTextView()
        setToolBar()
        addnotification()
        setSelectedPicture()
    }
    // MARK: - 关闭
    @objc private func close(){
//        textView.endEditing(true)
        self.textView.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }
//     MARK: - 设置头部title
    private func setupTitle(){
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        if let userName = HMUserAccountViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(userName)"
            let strm = NSMutableAttributedString(string: titleText)
            let rang = (titleText as NSString).range(of: userName)
            strm.addAttributes([NSFontAttributeName : UIFont.boldSystemFont(ofSize: 12),NSForegroundColorAttributeName : UIColor.orange], range: rang)
            titleLabel.text = titleText
        }else{
        titleLabel.text = "发布微博"
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }
// MARK: - 设置发送按钮
    private func setSendUIBarButton(){
        self.navigationItem.rightBarButtonItem = sendBarButtonItem
    }
    lazy var sendBarButtonItem: UIBarButtonItem = {
//        frame: CGRect(x: 0, y: 0, width: 30, height: 30)
        let btn = UIButton()
        btn.setTitle("发送", for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.addTarget(self, action: #selector(clickSendButton), for: .touchUpInside)
        btn.sizeToFit()
        let item = UIBarButtonItem(customView: btn)
        item.isEnabled = false
        return item
    }()
    // MARK: - 点击发送按钮
    @objc private func clickSendButton(){
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        let token = HMUserAccountViewModel().access_token
        let status = textView.imageEmoticon2Chs()//self.textView.text
        
        let program = ["access_token" : token,
                       "status" : status]
       
        SVProgressHUD.show()
        if selectColVC.selectedimgArr.count == 0 {
            HMNetworkingTools.shared.request(method: .POST, urlString: urlString, parameter: program, finishedBlock:{(response,error) -> () in
                
                if error != nil {
                    SVProgressHUD.showError(withStatus: "微博发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "成功")
                self.sendMircBlogSucceed()
            })
        }else{
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json" 
                //将需要上传的文件的二进制数据拼接到formdata中
                //withFileData: 需要上传的文件的二进制数据
                //name: 服务器接收的字段 "pic"
                //fileName: 服务器存储的名称, 不过新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
                //mimeType: 标识文件类型 application/octet-stream 任意类型
//            /Users/apple/Desktop/webbo/webo/webo/Classes/View/Compose/Controller/HMComposeViewController.swift:106:97: Cannot convert value of type '(_) -> _' to expected argument type '((AFMultipartFormData) -> Void)?'
            HMNetworkingTools.shared.post(urlString, parameters: program, constructingBodyWith: { (formdata) in
                
                for (index,img) in self.selectColVC.selectedimgArr.enumerated() {
                    print(index)
                    let imgdata = UIImagePNGRepresentation(img)!
                    //                let str = "\r\n"
                    //                imgDatas.append(str.data(using: .utf8)!)
              formdata.appendPart(withFileData: imgdata, name: "pic", fileName: "xxx", mimeType: "application/octet-stream")
                
                }
                
            }, progress: nil, success: { (succsetask, succsess) in
                SVProgressHUD.showSuccess(withStatus: "send microblog successed")
              self.sendMircBlogSucceed()
            }, failure: { (successtask, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "send microblog error")
            })
        }
            
    }
    private func sendMircBlogSucceed(){
        let hmtabVC = UIApplication.shared.keyWindow?.rootViewController as? HMTabBarController
       let hmnvVC = hmtabVC?.childViewControllers[0] as? HMNaviViewController
        let hmhomeVC = hmnvVC?.childViewControllers.first as? HMHomdController
        hmhomeVC?.loadData()
        self.close()
    }
    
    lazy var keyboardhView: HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    
    lazy var textView: UITextView = {
        let tv = UITextView()
//        tv.text = "I have only one month"
        tv.font = UIFont.systemFont(ofSize: 18)
        tv.textColor = UIColor.darkGray
        tv.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
        tv.keyboardDismissMode = .onDrag
        tv.alwaysBounceVertical = true
        return tv
    }()
    lazy var placeholdertext: UILabel = {
        let l = UILabel()
        l.text = "I have only one month"
        l.textColor = UIColor.gray
        l.font = UIFont.italicSystemFont(ofSize: 18)
        return l
    }()

    lazy var toolbar: UIStackView = {
        let t = UIStackView()
        t.axis = .horizontal
        t.distribution = .fillEqually
//        t.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
        
        return t
    }()
    
    lazy var selectColVC: HMComposeCollectionController = {
        let l = UICollectionViewFlowLayout()
        l.minimumLineSpacing = comMargin
        l.minimumInteritemSpacing = comMargin
        l.itemSize = CGSize(width: comColwidth, height: comColwidth)
        let ColVC = HMComposeCollectionController(collectionViewLayout: l)
        ColVC.view.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        ColVC.collectionView?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        return ColVC
    }()
    
    // TODO: - classEnd
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
extension HMComposeViewController: UITextViewDelegate{
    
    // MARK: - 设置textview
     func addTextView(){
        self.view.addSubview(textView)
        textView.delegate = self
        self.textView.addSubview(placeholdertext)
        let height = ScreenHeight / 3
        
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self.view)
            make.height.equalTo(height)
        }
        placeholdertext.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.leading.equalTo(textView).offset(5)
        }
        
    }
    
    func textViewDidChange(_ textView: UITextView) {
      sendBarButtonItem.isEnabled = textView.hasText
        placeholdertext.isHidden = textView.hasText
        
    }
}

extension HMComposeViewController{
    // MARK: - 设置toolbar
    func setToolBar(){
    
        self.view.addSubview(toolbar)
        toolbar.snp.makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(40)
        }
        //添加按钮
        let imageNames:[String] = ["compose_toolbar_picture",
                                   "compose_mentionbutton_background",
                                   "compose_trendbutton_background",
                                   "compose_emoticonbutton_background",
                                   "compose_add_background"]
        for (index,str) in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage.init(named: str), for: .normal)
            btn.tag = index + btnTag
            btn.addTarget(self, action: #selector(clicktoobarBtn(btn:)), for: .touchUpInside)
            btn.setTitleColor(UIColor.white, for: .normal)
            btn.backgroundColor = UIColor.gray
            toolbar.addArrangedSubview(btn)
        }
        
        
    }
    // MARK: - toolbar点击事件
    @objc private func clicktoobarBtn(btn: UIButton){
//        print(btn.tag)
        let style = toolStyle.init(rawValue: btn.tag)!
        switch style {
        case .Picture:
            print("点击图片")
selectColVC.addBtnIsClicked(cell: nil)
        case .Atsome:
            print("告诉某人")
        case .Topic:
            print("gg某人")
        case .Emotion:
//            print("点击表情")
            textView.inputView = textView.inputView == nil ? keyboardhView : nil
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            textView.reloadInputViews()
        case .More:
            print("点击更多")
        }
    }
    
    // MARK: - 添加通知
    func addnotification(){
//    UIKeyboardWillChangeFrame
        NotificationCenter.default.addObserver(self, selector: #selector(receiveNotification(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
       
        NotificationCenter.default.addObserver(self, selector: #selector(receiveNotificationKSelectEmoticon(noti:)), name: NSNotification.Name(rawValue: KSelectEmoticon), object: nil)
        
    }
    @objc private func receiveNotificationKSelectEmoticon(noti: Notification){
        print(noti)
        let em = noti.object as? HMEmoticon
        
        textView.inputEmoticon(emoticon: em)
    }
    @objc private func receiveNotification(noti: NSNotification){
//        print(noti)
        let info = noti.userInfo
        let rect = info?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        let offset = rect.origin.y - ScreenHeight
       toolbar.snp.updateConstraints { (make) in
        make.bottom.equalTo(self.view).offset(offset)
        }
    UIView.animate(withDuration: 0.25) {
        self.view.layoutIfNeeded()
        }
    
    }
    
     func setSelectedPicture(){
        self.addChildViewController(selectColVC)
        self.view.addSubview(selectColVC.view)
        selectColVC.view.snp.makeConstraints { (make) in
            make.top.equalTo(textView.snp.bottom)
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(toolbar.snp.top)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        selectColVC.view.isHidden = (selectColVC.selectedimgArr.count == 0)
    }
 
    
}





